
/* 
 * 1. 策略模式通过execute方法，将算法类和算法使用类解耦
 * 2. 简化了单元测试
 */

/* 
 * 可以将策略模式和简单工厂模式相结合
 * 将Context和Factory类融合在一起
 * class StrategyFactory {
 * Strategy strategy;
 * 
 * public Strategy createStrategy(String string) {
 * switch (string) {
 * case "a":
 * return new StrategyA();
 * case "b":
 * return new StrategyB();
 * default:
 * return new StrategyA();
 * }
 * }
 * public void execute() {
 * strategy.getResult();
 * }
 * }
 */
public class StrategyPattern {

    public static void main(String[] args) {
        Strategy a=new StrategyA();
        StrategyContext context=new StrategyContext(a);
        context.execute();
    }
}



class StrategyContext {
    Strategy strategy;

    public StrategyContext(Strategy strategy) {
        this.strategy = strategy;
    }

    /*
     * 使用execute代替getResult可以在从getResult迁移到其他算法时不用修改主要代码
     * 
     * 如添加了新的算法 getResultA 只需将下列方法修改为
     * public void execute(){
     * strategy.getResultA();
     * }
     */
    public void execute() {
        strategy.getResult();
    }
}

interface Strategy {
    void getResult();
}

class StrategyA implements Strategy {
    public void getResult() {
        System.out.println("A");
    }
}

class StrategyB implements Strategy {
    public void getResult() {
        System.out.println("B");
    }
}